
package stcu.control;

import stcu.*;
import stcu.forms.LoginForm;
import stcu.robjects.Login;

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.net.*;

public class ControlledLoginForm extends LoginForm {

    private JFrame self = this;
    private ClientAuth auth;

    public ControlledLoginForm(final ClientAuth auth) {
        this.auth = auth;
        setTitle("Shut the Chat Up");
        addListeners();
    }

    private void addListeners() {
        auth.addListener(new Handler());

        loginButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                final String id = idNumber.getText();
                // TODO: Check if text field is empty
                loginButton.setEnabled(false);

                new Thread() { public void run() {
                    try {
                        auth.login(id);
                    } catch (NoServerException e2) {
                        JOptionPane.showMessageDialog(self, 
                            "No server found",
                            "Login Failed",
                            JOptionPane.WARNING_MESSAGE);
                        loginButton.setEnabled(true);
                    }
                }}.start();
            }
        });

        idNumber.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                String id = idNumber.getText();
                loginButton.setEnabled(false);
                String message = idNumber.getText();

                if (message.isEmpty()){
                    return;
                }
                auth.login(id);
            }
        });
    }

    @Override
    public void setVisible(boolean visible) {
        loginButton.setEnabled(visible);
        super.setVisible(visible);
    }

    class Handler implements ClientAuth.Listener {
        public void fail(String msg) {
            JOptionPane.showMessageDialog(self, msg,
                    "Login Failed",
                    JOptionPane.ERROR_MESSAGE);
            loginButton.setEnabled(true);
        }

        public void success(Login.Status status) { }

        public void logout() { }
    }
}
